package com.voodoo.lib_frame.base;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.voodoo.lib_frame.Config;
import com.voodoo.lib_frame.R;
import com.voodoo.lib_frame.manager.FActivityManager;
import com.voodoo.lib_frame.receiver.NetBroadcastReceiver;
import com.voodoo.lib_frame.tip.XToastUtils;
import com.voodoo.lib_utils.L;
import com.voodoo.lib_utils.NetUtil;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.List;

import butterknife.ButterKnife;

/**
 * Author: voodoo
 * CreateDate: 2019/12/5 005 03:06 下午
 * Description: 所有Activity的基类
 */
public abstract class BaseActivity extends AppCompatActivity implements BaseView, NetBroadcastReceiver.NetEvent {

    private FrameLayout contentFlayout; // 所有控件的父布局
    private Toast toast;
    private boolean isShowProgress; // 是否正在显示加载框Progress
    private ProgressDialog progressDialog;

    public NetBroadcastReceiver netBroadcastReceiver;
    private int netMobile;
    WeakReference<Activity> weakReference;
    ConstraintLayout floatingButton;

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN); // 设置软键盘不遮挡布局
        setContentView(R.layout.activity_base);
        setBaseView(getLayoutResId()); // 设置加载的布局
        weakReference = new WeakReference<Activity>(this);
        FActivityManager.getInstance().addActivity(weakReference); // 将Activity添加到栈中
        ButterKnife.bind(this); // 注入绑定Activity
        registerNetBroadcastReceiver(); // 动态注册网络状态广播
        initViews();

        initData();
    }

    /**
     * 动态注册网络状态监听广播
     */
    private void registerNetBroadcastReceiver() {

        // 实例化IntentFilter对象
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
//        filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        netBroadcastReceiver = new NetBroadcastReceiver();
        netBroadcastReceiver.setNetEvent(this);
        registerReceiver(netBroadcastReceiver, filter);
    }

    /**
     * 判断网络是否链接
     *
     * @return {@code true}: 网络连接<br>{@code false}: 未连接网络
     */
    public boolean isNetConnect() {
        this.netMobile = NetUtil.getNetWorkState(BaseActivity.this);
        return netMobile == 0 || netMobile == 1 || netMobile == 2;
    }

    private void initProgressDialog() {
        // 初始化progressDialog，设置样式
        progressDialog = new ProgressDialog(this, R.style.loading_dialog);
        progressDialog.setIndeterminate(true);
        progressDialog.setCancelable(true);// 点击返回消失
        progressDialog.setCanceledOnTouchOutside(false);// 点击外部不可消失
    }

    private void setBaseView(final int layoutResId) {
        contentFlayout = findViewById(R.id.baseActivity_content_flayout);

        // 悬浮按钮
        floatingButton = findViewById(R.id.floatingButton_jumpToOtherApp);
        if (!getCanToOtherApp()) {
            floatingButton.setVisibility(View.GONE);
        }
        floatingButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent launchIntent = getPackageManager().getLaunchIntentForPackage("ai.weride.vending");
//                Intent launchIntent = getPackageManager().getLaunchIntentForPackage("com.ruike.vendingmachine");
                if (launchIntent != null) {
                    launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(launchIntent);
                } else {
                    showToast("无此应用");
                }
            }
        });

        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View rootView = inflater.inflate(layoutResId, null);
        rootView.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));
        contentFlayout.addView(rootView);

        if (Config.isShowRootTitle) {
            TextView rootText = new TextView(this);
            rootText.setText(new StringBuffer().append("activity:").append(getClass().getSimpleName()));
            rootText.setTextColor(Color.parseColor("#00FFFF"));
            contentFlayout.addView(rootText);
        }

    }

    protected abstract boolean getCanToOtherApp();

    /**
     * 设置加载的布局文件
     *
     * @return LayoutResId
     */
    protected abstract int getLayoutResId();

    /**
     * 初始化View（设置View的初始值）
     */
    protected abstract void initViews();

    /**
     * 初始化数据（请求数据、模拟数据）
     */
    protected abstract void initData();

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    // ========================================== 跳转页面 =========================================

    /**
     * 跳转页面
     *
     * @param cls    目标页面
     * @param bundle 页面跳转携带参数，若不传参则置为null
     */
    public void startActivity(Class<?> cls, Bundle bundle) {
        Intent intent = new Intent(this, cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        L.iTag("跳转页面的记录", "当前页=" + this.getClass().getSimpleName(),
                "跳转页=" + cls.getSimpleName());
        startActivity(intent);
        overridePendingTransition(R.anim.page_intent_in_anim, R.anim.page_intent_out_anim);
    }

    /**
     * 带返回值的页面跳转
     *
     * @param cls         目标页面
     * @param bundle      页面跳转携带参数，若不传参则置为null
     * @param requestCode 请求码
     */
    public void startActivityForResult(Class<?> cls, Bundle bundle, int requestCode) {
        Intent intent = new Intent(this, cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent, requestCode);
        overridePendingTransition(R.anim.page_intent_in_anim, R.anim.page_intent_out_anim);
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.page_intent_in_anim, R.anim.page_intent_out_anim);
    }

    // ============================================ Click ==========================================

    /**
     * View的点击事件
     *
     * @param view View
     */
    public void onClick(View view) {
    }

    /**
     * View的长按事件
     *
     * @param view View
     */
    public void onLongClick(View view) {
    }

    // ============================================ Toast ==========================================

    /**
     * 展示Toast提示
     *
     * @param showMsg 提示消息
     */
    public void showToast(String showMsg) {
        if (toast != null) {
            toast.cancel();
        }
        toast = Toast.makeText(this, showMsg, Toast.LENGTH_LONG);
        toast.show();
    }

    /**
     * 正确提示
     *
     * @param tips 提示内容
     */
    protected void showRightTip(String tips) {
        XToastUtils.getInstance().toShowXToast(this, tips, R.drawable.icon_right_tip, 3000);
    }

    /**
     * 错误提示
     *
     * @param tips 提示内容
     */
    protected void showErrorTip(String tips) {
        XToastUtils.getInstance().toShowXToast(this, tips, R.drawable.icon_error_tip, 3000);
    }

    /**
     * 带图标的提示
     *
     * @param tips 提示消息
     */
    protected void showLongTip(String tips, int duration) {
        XToastUtils.getInstance().toShowXToast(this, tips, duration);
    }


    /**
     * 展示加载框
     *
     * @param loadingStr 加载框中提示内容
     */
    protected void showProgressDialog(String loadingStr) {
        showProgressDialog(loadingStr, false);
    }

    /**
     * 展示加载框
     *
     * @param loadingStr 加载框中提示内容
     * @param cancelable 点击弹窗外侧是否可关闭
     */
    protected void showProgressDialog(String loadingStr, boolean cancelable) {
        removeProgressDialog();
        isShowProgress = true;
        if (!isFinishing()) {
            initProgressDialog();
            progressDialog.show();
            View views = LayoutInflater.from(this).inflate(R.layout.view_loading_dialog, null);
            TextView loading_tv_content = views.findViewById(R.id.loading_tv_content);
            loading_tv_content.setText(loadingStr);
            progressDialog.setContentView(views);
            progressDialog.setCancelable(cancelable);
            progressDialog.setCanceledOnTouchOutside(cancelable);// 点击外部消失
        }
    }

    /**
     * 移除加载框
     */
    protected void removeProgressDialog() {
        isShowProgress = false;
        if (progressDialog != null && progressDialog.isShowing()) {

            progressDialog.dismiss();
            progressDialog = null;
        }
    }

    // ========================================== 软键盘 ==========================================

    /**
     * 点击EditText以外的控件隐藏软键盘
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View currentFocus = getCurrentFocus();
            if (isShouldHideInput(currentFocus, ev)) {
                InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (inputMethodManager != null) {
                    inputMethodManager.hideSoftInputFromWindow(currentFocus.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    /**
     * 是否需要隐藏软键盘
     *
     * @param view  点击的View
     * @param event Event
     * @return 是否隐藏软键盘
     */
    private boolean isShouldHideInput(View view, MotionEvent event) {
        if (view != null && view instanceof EditText) { // 如果View不为空并且View是EditText类
            int[] leftTop = {0, 0};
            // 获取输入框当前位置的左上角坐标
            view.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + view.getHeight();
            int right = left + view.getWidth();
            return !(event.getX() > left) || !(event.getX() < right) || !(event.getY() > top) || !(event.getY() < bottom);
        }
        return false;
    }

    // ============================================ API ============================================

    @Override
    public void onStarted(String loadingStr) {
    }

    @Override
    public void onLoading(long total, long current) {
    }

    @Override
    public void onComplete() {
        removeProgressDialog();
    }

    @Override
    public void onErrorTip(String errorStr) {
        removeProgressDialog();
        showErrorTip(errorStr);
    }

    @Override
    public void onSuccess(String requestUrl, String requestJsonStr) {
        removeProgressDialog();
    }

    @Override
    public void onFailure(String requestUrl, String requestMsg) {
        removeProgressDialog();
    }

    @Override
    public void onError(String requestUrl, String errorMsg) {
        removeProgressDialog();
    }

    @Override
    public void onError(String requestUrl, String errorMsg, String data) {
        removeProgressDialog();
    }

    @Override
    public void onException(Exception exception) {
        removeProgressDialog();
    }

    @Override
    public void onDownloadFailed(String requestUrl, Exception e) {
    }

    @Override
    public void onDownloadSuccess(String requestUrl, File file) {
    }

    @Override
    public void onDownloading(String requestUrl, long total, long progress) {
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (toast != null) {
            toast.cancel();
        }
//        XToastUtils.getInstance(this).toXToastCancal();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        removeProgressDialog();
        // 释放注册的网络状态广播监听
        unregisterReceiver(netBroadcastReceiver);
        netBroadcastReceiver.setNetEvent(null);
        netBroadcastReceiver = null;
        FActivityManager.getInstance().killActivity(this.getClass()); // 将Activity移除栈
    }


    private boolean isAvilible(Context context, String packageName) {
        final PackageManager packageManager = context.getPackageManager();
        // 获取所有已安装程序的包信息
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        for (int i = 0; i < pinfo.size(); i++) {
            // 循环判断是否存在指定包名
            if (pinfo.get(i).packageName.equalsIgnoreCase(packageName)) {
                return true;
            }
        }
        return false;
    }

}
